package com.china08.yxyapi.service.manage.tec.teaching.lecture.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.entity.db.res.YxyResBookContents;
import com.china08.yxyapi.entity.db.res.YxyResBookContentsKnoledges;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.service.manage.tec.teaching.lecture.LectureQuestionService;
import com.china08.yxyapi.util.YxyResUtil;

@Service
public class LectureQuestionServiceImpl implements LectureQuestionService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;

    @Autowired
    private YxyResUtil yxyResUtil;

    @Autowired
    private YxyResBookContentsRepository bookContentRepository;

    @Override
    public BoolQueryBuilder get(BoolQueryBuilder boolQueryBuilder, String level, String type, String questionType) {
        // 只查询未删除的
        TermQueryBuilder deleteBuilder = new TermQueryBuilder("deleteFlag", "0");
        boolQueryBuilder.must(deleteBuilder);
        // 只能查询不是私人的
        TermQueryBuilder viewScopeBuilder = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(viewScopeBuilder);
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            TermQueryBuilder builder = new TermQueryBuilder("difficultyLevel", level);
            boolQueryBuilder.must(builder);
        }
        if (type != null) {
            if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
                TermQueryBuilder builder = new TermQueryBuilder("srcType", type);
                boolQueryBuilder.must(builder);
            }
            if (StringUtils.isNotBlank(questionType) && !StringUtils.equals("all", questionType)) {
                TermsQueryBuilder builder = new TermsQueryBuilder("questionType", questionType);
                boolQueryBuilder.must(builder);
            }

        } else {
            // 目前只有 单选 和多选
            BoolQueryBuilder typeOr = new BoolQueryBuilder();
            TermQueryBuilder builder1 = new TermQueryBuilder("questionType", "1");
            TermQueryBuilder builder8 = new TermQueryBuilder("questionType", "8");
            typeOr.should(builder1);
            typeOr.should(builder8);
            boolQueryBuilder.must(typeOr);
        }
        return boolQueryBuilder;
    }

    @Override
    public ElasticYxyYxyQuesResource findByEsQuesId(String quesId) {
        GetQuery getQuery = new GetQuery();
        getQuery.setId(quesId);
        ElasticYxyYxyQuesResource elasticQues = elasticsearchTemplate.queryForObject(getQuery,
                ElasticYxyYxyQuesResource.class);
        return elasticQues;
    }

    // 查詢解答
    @Override
    public BoolQueryBuilder getJieDa(BoolQueryBuilder boolQueryBuilder, String level, String type,
            String... questionType) {
        // 只查询未删除的

        TermQueryBuilder deleteBuilder = new TermQueryBuilder("deleteFlag", "0");
        boolQueryBuilder.must(deleteBuilder);
        // 只能查询不是私人的
        TermQueryBuilder viewScopeBuilder = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(viewScopeBuilder);
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            TermQueryBuilder builder = new TermQueryBuilder("difficultyLevel", level);
            boolQueryBuilder.must(builder);
        }
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("srcType", type);
            boolQueryBuilder.must(builder);
        }
        if (questionType != null) {
            List<String> list = Arrays.asList(questionType);
            List<String> queryList = new ArrayList<String>();
            for (String string : list) {
                if (StringUtils.isNotBlank(string) && !StringUtils.equals("all", string)) {
                    queryList.add(string);
                }
            }
            if (queryList.size() > 0) {
                TermsQueryBuilder builder = new TermsQueryBuilder("questionType", queryList);
                boolQueryBuilder.mustNot(builder);
            }

        } else {
            // 目前只有 单选 和多选
            BoolQueryBuilder typeOr = new BoolQueryBuilder();
            TermQueryBuilder builder1 = new TermQueryBuilder("questionType", "1");
            TermQueryBuilder builder8 = new TermQueryBuilder("questionType", "8");
            typeOr.should(builder1);
            typeOr.should(builder8);
            boolQueryBuilder.must(typeOr);
        }
        return boolQueryBuilder;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByBookcontentAndLevelAndTypeAndQuestionType(String bookcontent,
            String bookId, String difficultyLevel, String type, String questionType, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 基本查询
        boolQueryBuilder = get(boolQueryBuilder, difficultyLevel, type, questionType);
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)
                && !StringUtils.equals("null", bookcontent)) {
            // 目录查询
            boolQueryBuilder = questionFindByBookcontent(boolQueryBuilder, bookcontent);
        }
        TermQueryBuilder viewScopeBuilder = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(viewScopeBuilder);
        // 按书---全部(shuid 不为kong bookcontentid 是空)
        if (StringUtils.isNoneBlank(bookId) && StringUtils.equals("all", bookcontent)) {
            List<YxyResBookContents> list = bookContentRepository.findByBookIdAndIsViewOrderByOrderNum(bookId, 1);
            if (CollectionUtils.isNotEmpty(list)) {
                List<Integer> allList2 = new ArrayList<Integer>();
                for (YxyResBookContents yxyResBookContents : list) {
                    String bookcontent1 = yxyResBookContents.getId();
                    List<Integer> allList = questionFindByBookcontent1(boolQueryBuilder, bookcontent1);
                    allList2.addAll(allList);
                }
                TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", allList2);
                boolQueryBuilder.must(builder);
            }
        }
        //
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

    public BoolQueryBuilder questionFindByBookcontent(BoolQueryBuilder boolQueryBuilder, String bookcontent) {
        // 找到这个目录下的所有子目录
        List<String> bookcontentList = yxyResUtil.findTocByTocParent(bookcontent);
        List<YxyResBookContentsKnoledges> bookContentsKnoledges = yxyResBookContentsKnoledgesRepository
                .findByBookContentIdIn(bookcontentList);
        if (bookContentsKnoledges.size() > 0) {
            List<Integer> knowIds = bookContentsKnoledges.stream().map(x -> x.getKnowledgeId())
                    .collect(Collectors.toList());
            TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knowIds);
            boolQueryBuilder.must(builder);
        } else {
            List<Integer> knoids = new ArrayList<Integer>();
            TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knoids);
            boolQueryBuilder.must(builder);
        }
        return boolQueryBuilder;
    }

    public List<Integer> questionFindByBookcontent1(BoolQueryBuilder boolQueryBuilder, String bookcontent) {
        // 找到这个目录下的所有子目录
        List<Integer> allList = new ArrayList<Integer>();
        List<String> bookcontentList = yxyResUtil.findTocByTocParent(bookcontent);
        List<YxyResBookContentsKnoledges> bookContentsKnoledges = yxyResBookContentsKnoledgesRepository
                .findByBookContentIdIn(bookcontentList);
        if (bookContentsKnoledges.size() > 0) {
            List<Integer> knowIds = bookContentsKnoledges.stream().map(x -> x.getKnowledgeId())
                    .collect(Collectors.toList());
            allList.addAll(knowIds);
        } else {
            List<Integer> knoids = new ArrayList<Integer>();
            allList.addAll(knoids);
        }
        return allList;
    }

    /**
     * 查询page
     * 
     * @param boolQueryBuilder
     * @param pageable
     * @return
     */
    private Page<ElasticYxyYxyQuesResource> getPage(BoolQueryBuilder boolQueryBuilder, Pageable pageable) {
        SearchQuery query = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(boolQueryBuilder).build();
        Page<ElasticYxyYxyQuesResource> page = elasticsearchTemplate.queryForPage(query,
                ElasticYxyYxyQuesResource.class);
        return page;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByBookcontentAndLevelAndTypeAndQuestionTypeNotIn(
            String bookcontent, String bookId, String difficultyLevel, String type, List<String> quesTypeList,
            Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        String[] aStrings = {};
        aStrings = quesTypeList.toArray(aStrings);
        boolQueryBuilder = getJieDa(boolQueryBuilder, difficultyLevel, type, aStrings);
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            // 目录查询
            boolQueryBuilder = questionFindByBookcontent(boolQueryBuilder, bookcontent);
        } else {
            List<YxyResBookContents> list = bookContentRepository.findByBookIdAndIsViewOrderByOrderNum(bookId, 1);
            if (CollectionUtils.isNotEmpty(list)) {
                List<Integer> allList2 = new ArrayList<Integer>();
                for (YxyResBookContents yxyResBookContents : list) {
                    String bookcontent1 = yxyResBookContents.getId();
                    List<Integer> allList = questionFindByBookcontent1(boolQueryBuilder, bookcontent1);
                    allList2.addAll(allList);
                }
                TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", allList2);
                boolQueryBuilder.must(builder);
            }
        }
        TermQueryBuilder viewScopeBuilder = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(viewScopeBuilder);
        //
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

}
